package cn.chendd.cofig.filters;

import cn.chendd.logger.GatewayLogger;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * request请求耗时全局过滤器
 *
 * @author chendd
 * @date 2022/12/27 21:12
 */
@Component
public class RequestConsumeMillisecondsFilter implements GlobalFilter , Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //记录开始时间
        StopWatch start = StopWatch.createStarted();
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            //获取请求地址，记录结束时间
            String rawPath = exchange.getRequest().getURI().getRawPath();
            long time = start.getTime(TimeUnit.MILLISECONDS);
            GatewayLogger.getLogger().debug("request {} consume {} milliseconds" , rawPath , time);
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1000;
    }
}
